package com.tianji.promotion.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tianji.common.domain.dto.PageDTO;
import com.tianji.promotion.domain.query.CodeQuery;
import com.tianji.promotion.entity.Coupon;
import com.tianji.promotion.entity.ExchangeCode;
import com.tianji.promotion.mapper.ExchangeCodeMapper;
import com.tianji.promotion.service.IExchangeCodeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.promotion.utils.CodeUtil;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static com.tianji.promotion.domain.key.RedisKey.COUPON_CODE_SERIAL_KEY;

/**
 * <p>
 * 兑换码 服务实现类
 * </p>
 *
 * @author xianggu
 * @since 2023-06-03
 */
@Service
public class ExchangeCodeServiceImpl extends ServiceImpl<ExchangeCodeMapper, ExchangeCode> implements IExchangeCodeService {

    private BoundValueOperations<String, String> valueOps;

    public ExchangeCodeServiceImpl(StringRedisTemplate redisTemplate) {
        this.valueOps =  redisTemplate.boundValueOps(COUPON_CODE_SERIAL_KEY);
    }

    /**
     * 兑换码生成
     *
     * @param coupon
     */
    @Override
    @Async("getExecutor")
    public void autoEchangeCode(Coupon coupon) {
        //1.获取兑换码条数
        Integer num = coupon.getTotalNum();
        //2.redis执行自增
        Long count = valueOps.increment(num);
        if (count == null){
            return;
        }
        int redisCount = count.intValue();
        List<ExchangeCode> list = new ArrayList<>();
        //3.获取兑换码
        for (int i = redisCount - num +1; i < redisCount; i++) {
            String xxCode = CodeUtil.generateCode(i, 1000);
            //3.1 封装数据库po
            ExchangeCode e = new ExchangeCode();
            e.setCode(xxCode);
            e.setId(i);
            e.setExchangeTargetId(coupon.getId());
            e.setExpiredTime(coupon.getIssueEndTime());
            list.add(e);
        }
        //4.执行save
        this.saveBatch(list);
    }

    /**
     * 查询兑换码接口
     *
     * @param query
     * @return
     */
    @Override
    public PageDTO<ExchangeCode> queryCodeByPage(CodeQuery query) {
        //1.分页查询
        Integer status = query.getStatus();
        Long couponId = query.getCouponId();
        Page<ExchangeCode> page = this.lambdaQuery()
                .eq(ExchangeCode::getStatus, status)
                .eq(ExchangeCode::getExchangeTargetId, couponId)
                .page(query.toMpPageDefaultSortByCreateTimeDesc());
        return PageDTO.of(page);
    }
}
